package TryCode.UDP;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class UDPClient {
    public static void main(String[] args) {
        try {
            // 创建DatagramSocket对象
            DatagramSocket clientSocket = new DatagramSocket();

            // 获取服务器的IP地址
            InetAddress serverAddress = InetAddress.getByName("localhost");

            byte[] sendData = new byte[1024];
            byte[] receiveData = new byte[1024];
            Scanner scanner = new Scanner(System.in);
            // 要发送给服务器的消息
            String message = "Hello from client";
            sendData = message.getBytes();
            DatagramPacket receivePacket;
            // 创建发送数据的DatagramPacket对象
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, 5000);

            // 发送数据包给服务器
            clientSocket.send(sendPacket);
            while (true){
                receivePacket = new DatagramPacket(receiveData, receiveData.length);
                // 创建接收服务器响应的DatagramPacket对象
                // 接收服务器的响应
                clientSocket.receive(receivePacket);

                // 从接收的数据包中获取服务器响应
                String serverResponse = new String(receivePacket.getData());

                System.out.println("Received from server: " + serverResponse.replace("\u0000",""));

                String str = scanner.nextLine();
                clientSocket.send(new DatagramPacket(str.getBytes(), str.getBytes().length, serverAddress, 5000));
            }

            // 关闭Socket连接
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
